挑選一個 modal 放入 HTML,並把 id 改成 edit
<div class="modal fade" id="edit" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary"
data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
把控制項貼到對應的按鈕,注意 data-target
要對應 modal 的 id
<div class="col-md-9 text-right">
<button type="button" class="btn btn-outline-success"
data-toggle="modal"
data-target="#edit">
<i class="fas fa-shopping-cart mr-2 "></i>
這是按鈕
</button>
</div>
加上JQ設定
$('#edit').on('show.bs.modal', function (e) {
//show.bs.modal = BS內建,觸發時執行
let btn = $(e.relatedTarget);
console.log(btn);//確認點擊到哪個按鈕
});
按鈕的 data-title 是HTML5的屬性, data- 後面的名稱可以自定義
$('#edit').on('show.bs.modal', function (e) {
//show.bs.modal = BS內建,觸發時執行
let btn = $(e.relatedTarget);
// console.log(btn);//確認點擊到哪個按鈕
let title = btn.data('title');//取出按鈕的title
console.log(title);//確認title的內容
});
<div class="col-md-9 text-right">
<button type="button" class="btn btn-outline-success"
data-toggle="modal" data-target="#edit"
data-title="這是按鈕">
<i class="fas fa-shopping-cart mr-2 "></i>
這是按鈕
</button>
</div>
把 modal 的 title 換成按鈕上的 title
$('#edit').on('show.bs.modal', function (e) {
//show.bs.modal = BS內建,觸發時執行
let btn = $(e.relatedTarget);//抓取觸發按鈕的資料
// console.log(btn);//確認點擊到哪個按鈕
let title = btn.data('title');
// console.log(title);//確認title的內容
let modal = $(this);//要修改的modal就是現在開啟的這個modal
modal.find('.modal-title').text(title);
//把modal的title換成按鈕上的title
});
點擊每個有 data-toggle="modal" data-target="#edit"
的按鈕,可以看到modal的標題跟著按鈕變換
<div class="col-md-9 text-right">
<button type="button" class="btn btn-outline-success"
data-toggle="modal" data-target="#edit"
data-title="這也是按鈕">
<i class="fas fa-shopping-cart mr-2 "></i>
這也是按鈕
</button>
</div>
避免點點擊外圍區塊關閉,在modal最外層加上data-backdrop="static"
關閉此功能 即可
<div class="modal fade" id="edit"
data-backdrop="static" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLabel"
aria-hidden="true">